<script setup lang="ts">
import { ref, onMounted, computed, watch } from 'vue';
import VideoJS, { VideoJsPlayer } from 'video.js'; // 引入video.js

// 定义组件props
const props = defineProps<{
  id: string // 元素id
  videoUrl: string // 视频地址
  posterUrl?: string // 视频封面
}>();

// 解构出组件的props
const {
  id = 'my-video',
  videoUrl,
  posterUrl,
} = props;

// 元素引用
const videoRef = ref(null);
let player: VideoJsPlayer;
onMounted(() => {
  // 初始化video.js
  player = VideoJS(id, {
    muted: true, // 设置静音
    width: 600, // 视频宽度
    loop: true, // 循环播放
  }, () => { // video.js初始化回调
    console.log('videojs初始化成功');
  });

  // 播放视频
  player.play();
})

// 资源类型
const sourceType = computed(() => {
  return playUrl.value.includes('.m3u8') ? 'application/x-mpegURL' : 'video/mp4'
})

const play = (url: string) => {
  player.src(url);
  player.play();
}

const playUrl = ref(videoUrl);
watch(() => props.videoUrl, (newVal) => {
  playUrl.value = newVal;
})

// 将子组件的方法暴露出去
defineExpose({
  play
});
</script>

<template>
    <video ref="videoRef" :id="id" class="video-js" :poster="posterUrl" controls>
        <source :src="playUrl" :type="sourceType" />
    </video>
</template>

<style scoped>

</style>
